package experiment.e06.code;

import java.util.Iterator;
import java.util.TreeSet;

/**
 * @author thinkpad - 83start
 * @version v1.0
 * @create 2022/10/20 16:22
 * @package experiment.e06.code
 * @description 实验三
 * 修改题2中的Book类实现Comparable接口，该接口中对isbn进行排序，
 * 创建5个相应的对象，用TreeSet类的对象来存储这5个对象，输出存储的这5个对象(排序后)。
 */

public class Ch03 {
    public static void main(String[] args) {
        // 创建 Book 数组
        Book2[] books = new Book2[5];
        books[0] = new Book2("123-322-323", "活着", "余华");
        books[1] = new Book2("123-827-281", "兄弟", "余华");
        books[2] = new Book2("872-291-298", "在风雨中呐喊", "余华");
        books[3] = new Book2("425-222-212", "许三观卖血记", "余华");
        books[4] = new Book2("198-322-323", "一地一鸡毛", "刘震云");

        // 创建 TreeSet
        TreeSet<Book2> book2TreeSet = new TreeSet<>();
        // TreeSet 添加 book 元素
        for (int i = 0; i < books.length; i++) {
            book2TreeSet.add(books[i]);
        }

        // 迭代输出元素
        Iterator<Book2> iterator = book2TreeSet.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}

/**
 * Book 类
 * 实现 Comparable 接口
 */
class Book2 implements Comparable<Book2> {
    private String isbn;
    private String title;
    private String author;

    public Book2(String isbn, String title, String author) {
        this.isbn = isbn;
        this.title = title;
        this.author = author;
    }

    public String getIsbn() {
        return isbn;
    }


    public String getTitle() {
        return title;
    }


    public String getAuthor() {
        return author;
    }


    @Override
    public String toString() {
        return "Book{" +
                "isbn='" + isbn + '\'' +
                ", title='" + title + '\'' +
                ", author='" + author + '\'' +
                '}';
    }


    /**
     * 重写 compareTo 接口
     * @param book2
     * @return
     */
    @Override
    public int compareTo(Book2 book2) {
        return this.isbn.compareTo(book2.getIsbn());
    }
}